package org.testis.gui.mvc.view.testdesign;

import org.testis.gui.mvc.view.*;
import org.testis.gui.mvc.utilities.Validatable;
import org.testis.gui.mvc.controller.testdesign.PostConditionCaseController;
import org.testis.gui.mvc.controller.TestDesignControllerList;
import org.testis.gui.mvc.utilities.ValidationUtils;
import java.awt.Frame;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import org.orm.PersistentException;


/**
 *
 * @author  Cahit Emir Erel
 */
public class PostConditionCaseView extends AtofBaseDialog implements
    AbstractViewPanel, Validatable
{

    private static final long serialVersionUID = 7766422L;
    private boolean m_editMode;
    private String m_windowTitle;


    /** Creates new form AddTestPlanView */
    public PostConditionCaseView(Frame parent,
                                  boolean modal,
                                  boolean editMode)
    {
        super(parent,
              modal);
        m_editMode = editMode;
        if (editMode) {
            m_windowTitle = "Edit PostCondition Case";
        }
        else {
            m_windowTitle = "Add PostCondition Case";
        }
        initComponents();
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        nameLabel = new javax.swing.JLabel();
        nameTextField = new javax.swing.JTextField();
        descriptionLabel = new javax.swing.JLabel();
        descriptionTextField = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        criticalLabel = new javax.swing.JLabel();
        criticalChoice = new java.awt.Choice();
        timeoutLabel = new javax.swing.JLabel();
        timeoutTextField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(m_windowTitle);
        setModal(true);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        nameLabel.setFont(new java.awt.Font("Dialog", 0, 11));
        nameLabel.setText("* Name:");

        nameTextField.setFont(new java.awt.Font("Dialog", 0, 11));
        nameTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameTextFieldActionPerformed(evt);
            }
        });
        nameTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                nameTextFieldFocusLost(evt);
            }
        });

        descriptionLabel.setFont(new java.awt.Font("Dialog", 0, 11));
        descriptionLabel.setText("Description:");

        descriptionTextField.setFont(new java.awt.Font("Dialog", 0, 11));
        descriptionTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                descriptionTextFieldActionPerformed(evt);
            }
        });
        descriptionTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                descriptionTextFieldFocusLost(evt);
            }
        });

        String label;
        if (m_editMode) {
            label = "Save Changes";
        } else {
            label = "Add PostCondition Case";
        }
        saveButton.setText(label);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        criticalLabel.setFont(new java.awt.Font("Dialog", 0, 11));
        criticalLabel.setText("* Critical:");

        criticalChoice.add("false");
        criticalChoice.add("true");
        criticalChoice.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                criticalChoiceItemStateChanged(evt);
            }
        });

        timeoutLabel.setFont(new java.awt.Font("Dialog", 0, 11));
        timeoutLabel.setText("Total Timeout:");

        timeoutTextField.setEditable(false);
        timeoutTextField.setFont(new java.awt.Font("Dialog", 0, 11));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(criticalLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)
                                .addGap(17, 17, 17))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(nameLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE)
                                    .addComponent(descriptionLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(descriptionTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(criticalChoice, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE)))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(timeoutLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(timeoutTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE))
                    .addComponent(saveButton))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nameLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(descriptionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(descriptionLabel))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(criticalLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(criticalChoice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(timeoutLabel)
                    .addComponent(timeoutTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(saveButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void nameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameTextFieldActionPerformed
        try {
            TestDesignControllerList.newInstance().
                getPostConditionCaseController().operationChangeName(nameTextField.getText());
        } catch (Exception e) {
        //  Handle exception
        }
    }//GEN-LAST:event_nameTextFieldActionPerformed


    private void nameTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_nameTextFieldFocusLost
        try {
            TestDesignControllerList.newInstance().
                getPostConditionCaseController().operationChangeName(nameTextField.getText());
        } catch (Exception e) {
        //  Handle exception
        }
    }//GEN-LAST:event_nameTextFieldFocusLost


    private void descriptionTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_descriptionTextFieldActionPerformed
        try {
            TestDesignControllerList.newInstance().
                getPostConditionCaseController().operationChangeDescription(descriptionTextField.getText());
        } catch (Exception e) {
        //  Handle exception
        }
}//GEN-LAST:event_descriptionTextFieldActionPerformed


    private void descriptionTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_descriptionTextFieldFocusLost
        try {
            TestDesignControllerList.newInstance().
                getPostConditionCaseController().operationChangeDescription(descriptionTextField.getText());
        } catch (Exception e) {
        //  Handle exception
        }
}//GEN-LAST:event_descriptionTextFieldFocusLost


    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed

        WindowListener[] listeners = getWindowListeners();
        for (int i = 0; i < listeners.length; i++) {
            this.removeWindowListener(listeners[i]);
        }
        this.setEnabled(false);
        this.dispose();
        this.invalidate();
        TestDesignControllerList.newInstance().getPostConditionCaseController().
            operationCloseWindow();
    }//GEN-LAST:event_formWindowClosed


    private void criticalChoiceItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_criticalChoiceItemStateChanged

        TestDesignControllerList.newInstance().getPostConditionCaseController().
            operationChangeCritical(criticalChoice.getSelectedItem());
    }//GEN-LAST:event_criticalChoiceItemStateChanged


    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed

        if (!validateForm()) {
            return;
        }
        saveButton.setEnabled(false);
        if (m_editMode) {
            TestDesignControllerList.newInstance().
                getPostConditionCaseController().operationSavePostConditionCase(nameTextField.getText(),
                                                                                descriptionTextField.getText(),
                                                                                criticalChoice.getSelectedItem());
        }
        else {
            try {
                TestDesignControllerList.newInstance().getPostConditionCaseController().operationAddPostConditionCase(nameTextField.getText(), descriptionTextField.getText(), criticalChoice.getSelectedItem());
            } catch (PersistentException ex) {
                ex.printStackTrace();
            }
        }
        this.dispose();
    }//GEN-LAST:event_saveButtonActionPerformed
    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                TestPlanView dialog = new TestPlanView(new javax.swing.JFrame(), true);
//                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//                    public void windowClosing(java.awt.event.WindowEvent e) {
//                        System.exit(0);
//                    }
//                });
//                dialog.setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.awt.Choice criticalChoice;
    private javax.swing.JLabel criticalLabel;
    private javax.swing.JLabel descriptionLabel;
    private javax.swing.JTextField descriptionTextField;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JButton saveButton;
    private javax.swing.JLabel timeoutLabel;
    private javax.swing.JTextField timeoutTextField;
    // End of variables declaration//GEN-END:variables

    public void modelPropertyChange(PropertyChangeEvent evt)
    {
        if (evt.getPropertyName().equals(
            PostConditionCaseController.SHOW_ADD_POST_CONDITION_CASE)) {
            this.centerParent();
        }
        if (evt.getPropertyName().equals(PostConditionCaseController.CHANGE_NAME)) {
            nameTextField.setText(evt.getNewValue().toString());
        }
        else if (evt.getPropertyName().equals(
            PostConditionCaseController.CHANGE_DESCRIPTION)) {
            descriptionTextField.setText(evt.getNewValue().toString());
        }
        else if (evt.getPropertyName().equals(
            PostConditionCaseController.CHANGE_CRITICAL)) {
            criticalChoice.select(evt.getNewValue().toString());
        }
        else if (evt.getPropertyName().equals(
            PostConditionCaseController.CHANGE_TIMEOUT)) {
            timeoutTextField.setText(evt.getNewValue().toString());
        }
    }


    public boolean validateForm()
    {
        boolean valid = true;
        StringBuilder builder = new StringBuilder();
        if (ValidationUtils.isEmpty(nameTextField.getText())) {
            builder.append("Name must not be empty.\n");

            valid = false;
        }
        if (!valid) {
            JOptionPane.showMessageDialog(null,
                                          builder.toString(),
                                          "Error",
                                          JOptionPane.ERROR_MESSAGE);
        }
        return valid;
    }
}
